<script setup>
import { nextTick, ref } from 'vue'
import { onMounted } from "vue";
import {
  tagAddService,
  tagDeleteService, tagIdSelectNameService,
  tagSelectService,
  titleAddService,
  titleDeleteService, titleModifyService,
  titlePageService
} from "@/api/title.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {userAddService, userDeleteService, userPageService} from "@/api/user.js";
// import {MdEditor} from "md-editor-v3";
import _ from 'lodash';

import { MdPreview } from 'md-editor-v3';
// preview.css相比style.css少了编辑器那部分样式
import 'md-editor-v3/lib/preview.css';

import { solutionAddService } from '@/api/solution'
import { useAdminStore } from '@/store/admin';
import { provide } from 'vue';
const adminStore = useAdminStore()



onMounted(() => {
  //查询所有标签
  // loadTags()
})
/**
 * 查询题目信息
 * @type {Ref<UnwrapRef<*[]>, UnwrapRef<*[]> | *[]>}
 */
/**
 * 添加标签
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
const tagIdList = ref([])
//根据条件获取所有标签信息
const tagList = ref([])
const loading = ref(false)
const handleInputChange = (query) => {
  loading.value = true;
  setTimeout(() => {
    loadTag(query)
    loading.value = false;
  }, 500);
}
const loadTag = async (name) => {
  const res = await tagSelectService(1, 100000, name)
  tagList.value = res.data.data.list
}
 
 const contentModel = ref(false)
const showAddTitleModal = ref(false)
const tagName = ref('')
//查询所有标签
// const tagList = ref([])
// const loadTags = async() => {
//   const res = await tagSelectService()
//   if(res.data.status === 'success'){
//     tagList.value = res.data.data
//   }
// }
const addTag = async() => {
  if(tagName.value.length > 15){
    ElMessage.error('添加的标签名过长')
    return
  }
  const res = await tagAddService(tagName.value)
  if(res.data.status === 'success'){
    ElMessage.success('添加标签成功')
    tagName.value = ''
    // await loadTags()
    showAddTagModal.value = false
  }else{
    ElMessage.error(res.data.info)
  }
}
/**
 * 删除标签
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//删除标签
const delTagId = ref()
const deleteTag = async() => {
  const res = await tagDeleteService(delTagId.value)
  if(res.data.status === 'success'){
    ElMessage.success('删除标签成功')
    delTagId.value = ''
    // titleForm.value.selectIds = ''//重置添加标签选项
  }else{
    ElMessage.error(res.data.info)
  }
  // loadTags()
  showDeleteTagModal.value = false
}
//添加标签模态窗口
const showAddTagModal = ref(false)
//删除标签模态窗口
const showDeleteTagModal = ref(false)
// 创建表格数据
const titleInfo = ref([])
//删除标签id
const deleteId = ref('')
//增加题目表单
const titleForm = ref({
  titleName: '',
  titleContent: '',
  tagIds: []//要添加的taglist
})
//添加题目的校验规则
const titleFormRef = ref()
const titleRules = {
  titleName: [
    {required: true, message: '题目名称不能为空', trigger: 'blur'},
    {max: 30,message: '题目名不能超过30个字',trigger: 'blur'}
  ],
}
//添加题目
const addTitle = async(formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      const res = await titleAddService(titleForm.value)
      if(res.data.status === 'success'){
        showAddTitleModal.value = false
        await load()
        ElMessage.success('添加题目成功')
      }else{
        ElMessage.error(res.data.info)
      }
      titleForm.value.titleName= ''
      titleForm.value.titleContent= ''
      titleForm.value.tagIds= []
      titleFormRef.value.resetFields()
    }
  })
}
/**
 * 分页查询题目信息
 */
//分页查询底部导航栏和搜索框变量
const currentPage = ref(1)
const pageSize = ref(10)
const titleNameInput = ref('')
const total = ref(0)
const selectIds = Array

const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.titleId)
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const load = async () => {
  const res = await titlePageService(
    currentPage.value,pageSize.value,titleNameInput.value
  )
  if(res.data.status === 'success'){
    console.log(titleInfo.value)
    titleInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
  }else{
    ElMessage.error(res.data.info)
  }
}
/**
 * 删除题目
 */
const deleteTitle = async(titleId) => {
  // const titleIds = Array.of(titleId)
  ElMessageBox.confirm(
    '确定要删除该题目吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await titleDeleteService(titleId)
      if(res.data.status === 'success'){
        await load()
        ElMessage.success('删除成功')
      }else{
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//批量删除
const deleteTitles = async() => {
  //非空判断
  if(selectIds.value == null){
    ElMessage.info('未选中任何一道题目')
    return
  }
  if(selectIds.value != null && selectIds.value.length === 0){
    ElMessage.info('未选中任何一道题目')
    return
  }
  ElMessageBox.confirm(
    '确定要删除所有选中的题目吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await titleDeleteService(selectIds.value)
      if(res.data.status === 'success'){
        await load()
        ElMessage.success('删除成功')
      }else{
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 展示题目内容
 */
const showContent = ref(false)
const currentTitleContent = ref('')
const showContentModal = (titleContent) => {
  showContent.value = true
  currentTitleContent.value = titleContent
}
/**
 * 修改题目
 */
const modifyContentModel  = ref(false)

//是否打开修改题目模态窗口
const showModifyTitleModal = ref(false)
//修改题目表单
const modifyTitleForm = ref('')
//添加修改题目的校验规则
const modifyTitleFormRef = ref()
const modifyTitleRules = {
  titleName: [
    {required: true, message: '题目名称不能为空', trigger: 'blur'},
    {max: 30,message: '题目名不能超过30个字',trigger: 'blur'}
  ],
}
//修改题目方法
const openModifyModal = (modifyForm) => {
  //将当前的值赋值给要修改的表格（使用深拷贝，不然模态窗口后面的数据会一起改变）
  modifyTitleForm.value = _.cloneDeep(modifyForm)
  modifyTitleForm.value.tagIds = modifyForm.tags.map(item => item.tagId)
  delete modifyTitleForm.value.tags
  //通过标签id数据查询标签名称数组
  showModifyTitleModal.value = true
}
//发送请求
const modifyTitle = async(formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      const res = await titleModifyService(modifyTitleForm.value)
      if(res.data.status === 'success'){
        load()
        ElMessage.success('修改成功')
      }else{
        ElMessage.error(res.data.info)
      }
      showModifyTitleModal.value = false
    }
  })
}
//管理题解
const showSolution = ref(false)
const currentTitleId = ref()
const currentTitleName = ref()
provide('update-show',(value) => {
    showSolution.value = value
})
const openManageSolutionModal = async(title) => {
  currentTitleId.value = title.titleId
  currentTitleName.value = title.titleName
  showSolution.value = true
  // currentTitleId.value = titleId
}

</script>

<template>
<!--  模态窗口-->
<!--  添加题目模态窗口-->
  <div>
<!--    添加标签模态窗口-->
    <el-dialog v-model="showAddTagModal" title="添加标签" width="300">
      <el-form :model="titleForm" @submit.native.prevent>
        <el-form-item label="标签名称">
          <el-input v-model="tagName" autocomplete="off" @keyup.enter="addTag"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddTagModal = false">取消</el-button>
          <el-button type="primary" @click="addTag">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
<!--    删除标签模态窗口-->
    <el-dialog v-model="showDeleteTagModal" title="删除标签" width="300">
      <el-form>
        <el-select v-model="delTagId" clearable placeholder="查找并选择对应标签" style="width: 240px" filterable
         :remote-method="handleInputChange" :remote="true" :loading="loading">
          <el-option v-for="(item, index) in tagList" :key="index" :label="item.tagContent" :value="item.tagId" />
        </el-select>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteTagModal = false">取消</el-button>
          <el-button type="primary" @click="deleteTag">
            删除
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  添加题目模态窗口-->
    <el-dialog v-model="showAddTitleModal" title="添加题目" width="500">
      <el-form ref="titleFormRef" :rules="titleRules" :model="titleForm">
        <el-form-item prop="titleName" label="题目名称">
          <el-input v-model="titleForm.titleName" autocomplete="off" />
        </el-form-item>
        <el-button type="success" @click="showAddTagModal = true" style="float: left">添加标签</el-button>
        <el-button type="danger" @click="showDeleteTagModal = true" style="float: right">删除标签</el-button>
        <el-form-item prop="list" label="标签" :label-width="80">
        <el-select v-model="titleForm.tagIds" clearable placeholder="查找并选择对应标签" style="width: 240px" filterable
          :multiple="true" :remote-method="handleInputChange" :remote="true" :loading="loading">
          <el-option v-for="(item, index) in tagList" :key="index" :label="item.tagContent" :value="item.tagId" />
        </el-select>
      </el-form-item>
        <!-- <el-form-item label="标签" :label-width="50">
          <el-select v-model="titleForm.selectIds" :multiple-limit="5" multiple clearable placeholder="请选择一个标签">
            <el-option
            v-for="(item,index) in tagList"
            :key="index"
            :value="item.tagId"
            :label="item.tagName"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="题目内容">
                    <el-button @click="contentModel = true">填写内容</el-button>
                </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddTitleModal = false">取消</el-button>
          <el-button type="primary" @click="addTitle(titleFormRef)">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 填写题目内容模态窗口 -->
    <el-dialog v-model="contentModel" fullscreen top="40vh" width="70%" draggable>
            <span>题目内容</span>
            <template #footer>
                <div>
                    <v-md-editor v-model="titleForm.titleContent" height="400px" :include-level="[1, 2, 3, 4]"
                        :disabled-menus="[]" @upload-image="handleUploadImage" />
                </div>
                <div class="dialog-footer">
                    <el-button @click="contentModel = false">取消</el-button>
                    <el-button type="primary" @click="contentModel = false">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
<!--    展示题目内容模态窗口-->
    <el-dialog v-model="showContent" title="题目内容" width="800">
      <el-form>
        <MdPreview class="red" style="background: #3d3d3d" :modelValue="currentTitleContent">
        </MdPreview >
      </el-form>
    </el-dialog>
    <!--  修改题目模态窗口-->
    <el-dialog v-model="showModifyTitleModal" title="修改题目" width="500">
      <el-form ref="modifyTitleFormRef" :rules="modifyTitleRules" :model="modifyTitleForm">
        <el-form-item prop="titleName" label="题目名称">
          <el-input v-model="modifyTitleForm.titleName" autocomplete="off" />
        </el-form-item>
        <el-button type="success" @click="showAddTagModal = true" style="float: left">添加标签</el-button>
        <el-button type="danger" @click="showDeleteTagModal = true" style="float: right">删除标签</el-button>
        <el-form-item label="标签" :label-width="80">
        <el-select v-model="modifyTitleForm.tagIds" placeholder="查找并选择对应标签" style="width: 240px" filterable
          :multiple="true" :remote-method="handleInputChange" :remote="true" :loading="loading">
          <el-option v-for="(item, index) in tagList" :key="item.tagId" :label="item.tagContent" :value="item.tagId" />
        </el-select>
      </el-form-item>
        <el-form-item label="题目内容">
                    <el-button @click="modifyContentModel = true">填写内容</el-button>
                </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showModifyTitleModal = false">取消</el-button>
          <el-button type="primary" @click="modifyTitle(modifyTitleFormRef)">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改题目内容模态窗口 -->
    <el-dialog v-model="modifyContentModel" fullscreen top="40vh" width="70%" draggable>
            <span>新闻介绍</span>
            <template #footer>
                <div>
                    <v-md-editor v-model="modifyTitleForm.titleContent" height="400px" :include-level="[1, 2, 3, 4]"
                        :disabled-menus="[]" @upload-image="handleUploadImage" />
                </div>
                <div class="dialog-footer">
                    <el-button @click="modifyContentModel = false">取消</el-button>
                    <el-button type="primary" @click="modifyContentModel = false">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
  </div>
<!-- 管理题解模块 -->
  <SolutionList v-if="showSolution" :currentTitleId="currentTitleId" :currentTitleName="currentTitleName"></SolutionList>
  
  <div v-show="!showSolution">
<!--    功能框-->
    <el-card style="float: left;margin-bottom: 20px">
      <el-button type="primary" @click="showAddTitleModal = true">添加题目</el-button>
      <!-- <el-button type="danger" @click="deleteTitles">批量删除</el-button> -->
    </el-card>
    <!--    搜索框-->
    <el-card class="title-search">
      <span><h2>题目名称：</h2></span>
      <input v-model="titleNameInput" @keyup.enter.native="load">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div v-show="!showSolution">
    <el-table
      ref="multipleTableRef"
      :data="titleInfo"
      stripe
      style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="55" />
      <el-table-column property="titleId" label="编号" width="120"/>
      <el-table-column style="z-index: 100" property="titleName" label="题目名" width="150" >
        <template #default="scope">
          <div style="cursor: pointer;color: blue" @click="showContentModal(scope.row.titleContent)">{{scope.row.titleName}}</div>
        </template>
      </el-table-column>
      <el-table-column  property="tags.tagContent" label="标签" width="300" >
        <template #default="scope">
    <div>
      <!-- 合并并显示所有 tagContent -->
      <span v-for="(tag, index) in scope.row.tags" :key="index">
        {{ tag.tagContent }}<span v-if="index < scope.row.tags.length - 1">, </span>
      </span>
    </div>
  </template>
        </el-table-column>
      <el-table-column property="createTime" label="创建时间" width="180" />
      <el-table-column property="updateTime" label="最近修改时间" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="warning" size="small" @click="openManageSolutionModal(scope.row)">
            管理题解
          </el-button>
          <!-- <el-button type="success" size="small" @click="openSolutionModal(scope.row.titleId)">
            写题解
          </el-button> -->
          <el-button type="info" size="small" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteTitle(scope.row.titleId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10, 20]"
          size="large"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
/*搜索样式*/
.title-search{
  width: 400px;
  float: left;
  margin-left: 20px;
}
.title-search span{
  float: left;
}
.title-search input{
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}
/*设置markdown字体颜色*/
:deep() div.default-theme p{
  color: white;
}
/*表头样式*/
:deep() th.el-table__cell{
  color: black;
  font-size: 20px;
}
</style>
